<template>
  <div class="recyclebin-container">
    <a-tabs v-model:activeKey="delrecyKey" @change="tabChange">
      <a-tab-pane key="1" tab="删除栏目">
        <div class="add-site scrollBar">
          <base-tree
            :treeData="recycleTree"
            :checkStrictly="checkStrictly"
            :checkedKeys="checkMenuKeys"
            :fieldNames="fieldNames"
            @checked_Keys="checked_Keys"
            class="inlineTree"
            v-if="delrecyKey == 1"
          >
            <!-- <template #slotProps="{ id }">
                <a-tooltip placement="right" v-if="id == -1">
                  <template #title>
                       <span>选中后，用户可拥有后续新增子站点的权限</span>
                     </template>
                     <i class="iconfont icon-hint1" style="font-size: 16px; margin-left: 8px">
                     </i>
                </a-tooltip>
              </template> -->
          </base-tree>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="还原栏目">
        <div class="add-site scrollBar">
          <base-tree
            :treeData="recycleTree"
            :checkStrictly="checkStrictly"
            :checkedKeys="checkMenuKeys"
            :fieldNames="fieldNames"
            @checked_Keys="checked_Keys1"
            class="inlineTree"
            :selectable="false"
            v-if="delrecyKey == 2"
          >
            <!-- <template #slotProps="{ id }">
                <a-tooltip placement="right" v-if="id == -1">
                  <template #title>
                       <span>选中后，用户可拥有后续新增子站点的权限</span>
                     </template>
                     <i class="iconfont icon-hint1" style="font-size: 16px; margin-left: 8px">
                     </i>
                </a-tooltip>
              </template> -->
          </base-tree>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
  <div class="saveBtn" :style="styleWidth">
    <a-button
      style="margin-right: 16px"
      type="primary"
      :disabled="
        delrecyKey === '1'
          ? !btnPerm.includes('deleteAble') || isDisabled
          : !btnPerm.includes('restoreAble') || isDisabled
      "
      @click="saveSetting(1)"
    >
      {{ delrecyKey === "1" ? "删除栏目" : "还原栏目" }}
    </a-button>
    <a-button
      type="primary"
      @click="saveSetting(2)"
      :disabled="
        delrecyKey === '1'
          ? !btnPerm.includes('delAndConAble') || isDisabled
          : !btnPerm.includes('restoreAndConAble') || isDisabled
      "
    >
      {{ delrecyKey === "1" ? "删除栏目及内容" : "还原栏目及内容" }}
    </a-button>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, createVNode, watch } from "vue";
import { scrollType, dataSourceType } from "@/type.d";
import request from "@/api/index";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import baseTree from "@/components/tree/baseTree.vue";
import { routerPerm } from "@/utils/common";
const btnPerm = ref<any[]>([]);
const checkMenuKeys = ref<(string | number | any)[]>([]);
const delrecyKey = ref<number | string>("1");
const checkStrictly = ref<Boolean>(true); //树型节点选择不关联
const isDisabled = ref<Boolean>(true);
const fieldNames = reactive({
  title: "channelName",
  key: "id",
  disableCheckbox: "recycled",
});
//菜单数据
let recycleTree = ref<dataSourceType[]>([]);
// 获取站群
const getRecycleTree = async () => {
  const data = (await request.fetchChannelRecycledTreeList()) || {};
  checkMenuKeys.value = [];
  const loop = (data: dataSourceType[]) => {
    data.forEach((item: dataSourceType) => {
      // 如果recycled为false，意味着都不可编辑
      item.disableCheckbox = !item.recycled;
      let length = data.length;
      if (!item.children) {
        for (let i in data) {
          if (data[i].children) {
            length = 0;
          }
        }
        if (length >= 1) {
          item.class = "needInline";
        }
      }
      // item.selected = '';
      // if (item.selected) {
      //   checkMenuKeys.value.push(+item.id);
      // }
      if (item.children) {
        loop(item.children);
      }
    });
  };
  recycleTree.value = data;
  loop(recycleTree.value);
};

// 选择组织

const checked_Keys = (obj: dataSourceType) => {
  let checkedNode = obj.e.node;
  let datas = JSON.parse(JSON.stringify(recycleTree.value));
  loops(datas, obj.checkedKeys.checked);
  checkMenuKeys.value = obj.checkedKeys.checked;
  if (checkedNode && checkedNode.children) {
    checkMenuKeys.value = loopChildren([checkedNode] || [], obj.e.checked);
  } else {
    checkMenuKeys.value = obj.checkedKeys.checked;
  }
};
// 递归处理数据
const loops = (datalist: dataSourceType[] = [], ids: dataSourceType[] = []): any => {
  const loop1 = function (data: dataSourceType[]) {
    if (data instanceof Array && data.length) {
      for (var j = 0; j < ids.length; j++) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].id == ids[j]) {
            data.splice(i, 1);
          } else {
            if (data[i].children instanceof Array && data[i].children.length) {
              loop1(data[i].children);
            }
          }
        }
      }
    }
  };
  return loop1(datalist);
};

//递归处理数据
const loopChildren = (datalist: dataSourceType[] = [], checked: Boolean): any => {
  // 父级选中，子级全选
  // 递归遍历处理数据
  if (!checked) return;
  const record: (string | number)[] = [];
  const loop1 = function (data: dataSourceType[]) {
    if (data instanceof Array && data.length) {
      data.map((d) => {
        record.push(d.id);
        if (d.children instanceof Array && d.children.length) {
          loop1(d.children);
        }
      });
    }
  };
  loop1(datalist);
  return [...new Set(record)];
};

const loopParent = (
  data: dataSourceType[],
  Pid: number | string,
  isSelected: Boolean,
  selectedKey: (string | number)[]
) => {
  if (!isSelected) {
    return;
  }
  for (let i in data) {
    if (data[i].id == Pid) {
      !selectedKey.includes(data[i].id) ? selectedKey.push(data[i].id) : "";
      if (data[i].parentId) {
        loopParent(recycleTree.value, data[i].parentId, isSelected, selectedKey);
      }
    } else {
      if (data[i].children instanceof Array && data[i].children.length) {
        loopParent(data[i].children, Pid, isSelected, selectedKey);
      }
    }
  }
};
//还原
const checked_Keys1 = (obj: dataSourceType) => {
  console.log(obj, "obj");
  let isChecked = obj.e.checked;
  checkMenuKeys.value = obj.checkedKeys.checked;
  const loop = (data: dataSourceType) => {
    data.forEach((item: dataSourceType) => {
      if (!isChecked) {
        console.log(checkMenuKeys.value, "checkMenuKeys.valuecheckMenuKeys.value11");
        if (checkMenuKeys.value.includes(item.id)) {
          for (let i = 0; i < checkMenuKeys.value.length; i++) {
            item.id == checkMenuKeys.value[i] ? checkMenuKeys.value.splice(i, 1) : "";
          }
        }
      } else {
        console.log(checkMenuKeys.value, "checkMenuKeys.valuecheckMenuKeys.value");
        !checkMenuKeys.value.includes(item.id) ? checkMenuKeys.value.push(item.id) : "";
      }
      if (item.children instanceof Array && item.children.length) {
        loop(item.children);
      }
    });
  };
  console.log(checkMenuKeys.value, "checkMenuKeys.value");

  loop(obj.e.node.children || []);

  loopParent(recycleTree.value, obj.e.node.parentId, isChecked, checkMenuKeys.value);

  isDisabled.value = !checkMenuKeys.value.length ? true : false;
};

const tabChange = (e: any) => {
  getRecycleTree();
};

//还原栏目
const saveSetting = (type: number) => {
  if (delrecyKey.value === "1") {
    Modal.confirm(
      Object.assign({}, msgModal.confirm, {
        title: "删除确认",
        content: "删除栏目后，该栏目的所有子栏目都会被一并删除",
        icon: createVNode("i", {
          class: "iconfont icon-warn warning_ICON",
        }),
        okText: "删除",
        onOk: async () => {
          await deleteRecycleBin(type);
          Modal.destroyAll();
        },
        onCancel() {
          Modal.destroyAll();
        },
      })
    );
  } else {
    deleteRecycleBin(type);
  }
};

const deleteRecycleBin = async (type: number) => {
  const postData = {
    idSet: checkMenuKeys.value,
    type: type,
  };

  await request[
    delrecyKey.value === "1" ? "fetchChannelDelete" : "fetchChannelReduction"
  ](postData)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        getRecycleTree();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// watch
watch(
  () => checkMenuKeys.value,
  (newVal, oldVal) => {
    isDisabled.value = !newVal?.length ? true : false;
  }
);
//onmounted
onMounted(async () => {
  btnPerm.value = routerPerm();
  console.log(btnPerm.value);

  getRecycleTree();
  useFixeWidth();
});
</script>
<style lang="less" scoped>
.recyclebin-container {
  display: flex;
  flex-direction: row;
  padding: 16px;
  background: #ffffff;
  height: calc(100% - 120px);

  ::v-deep(.ant-tabs) {
    overflow: auto;
  }

  .add-site {
    height: 100%;
    width: 100%;
    overflow: auto;
    display: flex;
    flex-direction: column;
    padding-top: 22px;
    padding-bottom: 8px;
    font-size: 14px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);

    .add-site-tip {
      margin-top: 4px;
      display: flex;
      flex-direction: row;
    }
  }

  .add-site-tip-top {
    padding-top: 22px;
    padding-bottom: 8px;
    display: flex;
    flex-direction: row;
  }

  .section-tab {
    padding-top: 24px;
  }

  .document-tab {
    padding-top: 24px;
  }
}

.saveBtn {
  position: fixed;
  bottom: 0;
  height: 48px;
  background-color: #fff;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

::v-deep(.ant-tabs-content-holder) {
  overflow: auto;
}
</style>

<style lang="less">
.inlineTree {
  .ant-tree-list-holder-inner {
    display: block !important;

    .needInline {
      width: 14.28%;
      display: inline-flex;
      min-width: 150px;
    }
  }
}

.document-tab,
.section-tab {
  .ant-select-single {
    min-width: 130px;
  }
}
</style>
